package user.zc.config;

import user.zc.config.value.Key;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;


public abstract class KeyConfig implements IConfig<List<Key>> {
    protected ValueType type;
    private List<Key> data ;
    public KeyConfig(ValueType type) {
        this.type = type;
    }

    public List<Key> getData() {
        return data;
    }

    public void setData(List<Key> data){
        this.data = data;
    }

    public   List<Key> readEntity(String fileName, Class<Key> clazz)throws Exception{
        return readConfig(fileName,(line)->type.split(line,clazz));
    }

    private  List<Key> readConfig(String fileName, Function<String,Key> builder)throws Exception{
        List<Key> conf = new ArrayList<>();
        try(BufferedReader bufferedReader = getConfBufferedReader(fileName);){
            String line = null;
            while ((line =bufferedReader.readLine()) != null /*&& !"".equals(line)*/ ) {
                conf.add(builder.apply(line));
            }
        }
        return conf;
    }

    @Override
    public  boolean saveOrUpdate(String fileName, List<Key> collect)throws Exception{
        //新增是true,修改是false
        File file = getFile(fileName);
        boolean isNew = !file.exists();
        if(file.exists()){
            file.delete();
        }
        try(
                FileWriter fileWriter  = new FileWriter(file);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);){
            for (Key key : collect) {
                Map.Entry entry = new AbstractMap.SimpleEntry(key.getKey(),null);
                bufferedWriter.write(type.join(entry));
            }
            bufferedWriter.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
        return isNew;
    }

    protected abstract BufferedReader getConfBufferedReader(String fileName)throws Exception;
}
